package com.future.myjavatools.core.zhoupu;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.beanutils.BeanMap;
import org.modelmapper.ModelMapper;
import org.springframework.context.ApplicationContext;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Map;

/**
 * 代码描述
 * <p>
 *
 * @author 阿汤
 * @since 2019/12/3 11:43
 */
public abstract class ConvertUtils {

    public static ModelMapper getConverter() {
        ApplicationContext applicationContext = ApplicationContextUtils.getApplicationContext();
        Assert.notNull(applicationContext, "applicationContext is null");
        ModelMapper converter = applicationContext.getBean(ModelMapper.class);
        Assert.notNull(converter, "modelMapper is null");
        return converter;
    }

    /**
     * 单个对象转换
     *
     * @param from
     * @param toClass
     * @param <F>
     * @param <T>
     * @return
     */
    public static <F, T> T convertObject(F from, Class<T> toClass) {
        T to = getConverter().map(from, toClass);
        return to;
    }

    public static <F, T> void convertObject(F from, T to) {
        getConverter().map(from, to);
    }

    /**
     * 将对象装换为map
     *
     * @param bean
     * @return
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = Maps.newHashMap();
        if (bean != null) {
            BeanMap beanMap = new BeanMap(bean);
            for (Object key : beanMap.keySet()) {
                map.put(key + "", beanMap.get(key));
            }
        }
        return map;
    }

    /**
     * 将对象装换为map
     *
     * @param objList
     * @return
     */
    public static <T> List<Map<String, Object>> beanToMap(List<T> objList) {
        List<Map<String, Object>> list = Lists.newArrayList();
        if (objList != null && objList.size() > 0) {
            Map<String, Object> map = null;
            T bean = null;
            for(int i = 0; i < objList.size(); i++){
                bean = objList.get(i);
                if(null != bean) {
                    map = beanToMap(bean);
                    list.add(map);
                }
            }
        }
        return list;
    }



}
